<?php


namespace app\model;

use app\job\Capture;
use app\job\CaptureCal;
use app\job\CompareFeature;
use app\process\CalFeature;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use think\Model;
use fast\Http;
/**
 * 抓拍记录
 */
class Faces extends Model {

    /**
     * 1、更新摄像头最后出现时间
     * 2、保存face表、保存图片
     * 3、加入计算特征值队列
     * @param $content
     * @param $log_id
     * @param $time
     * @return true|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saev_face($content,$log_id=0,$time=0){
        Log::info($log_id."保存face表>>");
        // Log::debug($log_id."保存face表>>".$content);
        $content=json_decode($content,true);
        if(isset($content['FaceListObject']['FaceObject'])){
            $faces=$content['FaceListObject']['FaceObject'];
        }else{
            Log::error($log_id."无faceObject");
            return true;
        }

        Log::debug($log_id."保存face表>>faces数量：".count($faces));
        foreach ($faces as $face) {
            if(in_array($face['DeviceID'],['51107100981191603601','51107100981191601215','51107100981191601205'])){
                Log::info($log_id."保存face表>>指定：：：".$face['DeviceID']);
            }
            // Log::info("推送人像：".json_encode($face));
            //$path=config('capture_path').$face['DeviceID'].'/';
            $path=config('capture.capture_path').'/'.$face['DeviceID'].'/'.date('Ym').'/'.date('d').'/';
            $images=$face['SubImageList']['SubImageInfoObject'];
            $data['device_id']=$face['DeviceID'];
            Log::info($log_id."保存face表>>获取设备信息");
            $device=ViidDevice::where('device_id','=',$data['device_id'])->find();
            //有消息就更新最新数据时间
            ViidDevice::where('device_id',$device['device_id'])->save(['last_time'=>date('Y-m-d H:i:s')]);
            if($device){
                $aizone=Aizone::find($device['aizone_id']);
                $data['device_name']=$device['name'];
                $data['aizone_id']=$device['aizone_id'];
                $data['aizone_name']=$device['aizone_name'];
                $data['address_id']=$aizone['name_code'];
                $data['dwid']=$device['dwid'];
            }
            $data['face_id']=$face['DeviceID'].(microtime(true)*10000);
            $data['source_id']=$face['SourceID'];
            $data['img_bg']=$images[0]['ImageID'];
            $data['img_face']=$images[1]['ImageID'];
            $data['file_path']=$path;
            try {
                Log::info($log_id."保存face表>>首次保存face表");
                $data['create_time']=date("Y-m-d H:i:s",$time);
                $data['save_time']=date("Y-m-d H:i:s");
                $this->save($data);
                $data['id']=$this->id;
                //数据获取之后发送前台显示
                $data['longitude']=$device['longitude'];
                $data['latitude']=$device['latitude'];
                $push_face['msg_type']='faces';
                $push_face['data']=$data;
                Http::post('http://127.0.0.1:9503',['content'=>json_encode($push_face)]);
                Log::info($log_id."保存face:".json_encode($this->toArray()));
                save_base_img($this->id.'_bg',$images[0]['Data'],$path);
                save_base_img($this->id.'_face',$images[1]['Data'],$path);
                $job_data = [];
                $job_data["ts"] = time();
                $job_data["bizid"] = uniqid();
                $job_data["params"] =$this->id;
                $job_data["log_id"]=$log_id;
                Queue::push(CaptureCal::class,$job_data,'capture_cal_list');
            }catch (\Exception $e){
                Log::error($log_id."保存错误：".$e->getMessage()."\n".$e->getTraceAsString());
            }
        }
    }

    public function compare_by_face_id($id){
        $data=$this->find($id);
        $res=$this->compare(base64_img($data['file_path']));
        $res=json_decode($res,true);
        if($res['code']===0){
            $datas=$res['data']['results'];
            if(count($datas)>0){
                $single_data=$datas[0];
                MqttFacePushInfo::insert_compare_result(array_merge($single_data,$data->toArray()));
            }
        }
        return null;
    }

    /**
     * 比较底库
     * 先比较实名库，再比较未实名库，如果都没有，则放入未实名库
     * @param $photo
     * @return mixed
     */
    public function compare($photo,$data){
        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        //实名库比较
        $res=json_decode($service->compare_face($photo,1),true);
        Log::info("实名库比较结果：".json_encode($res));
        if($res&&$res['code']===0){
            $datas=$res['data']['results'];
            if(count($datas)>0){
                return $datas[0];
            }else{
                //未实名库比较
                /*$res=json_decode($service->compare_face($photo,2),true);
                if($res['code']===0) {
                    $datas = $res['data']['results'];
                    if (count($datas) > 0) {
                        return $datas[0];
                    } else {
                        if(!$data){
                            return [];
                        }else{
                            //创建人员放入未实名库
                            $face = new MqttUserManage();
                            $face->photo=$photo;
                            $face->ywlsh=$data['face_id'];
                            $face->name='';
                            $face->address=$data['aizone_name'];
                            $face->phone='';
                            $post_ai_return=$service->create_face($face,2);
                            /*$post_ai_return_array=json_decode($post_ai_return,true);
                            $photo_id=0;
                            if($post_ai_return_array['code']===0){
                                $res=$post_ai_return_array['data'];
                                $data['photo_id']=$res['photo_id'];
                                $data['album_id']=$res['album_id'];
                                $data['']
                            }*/
                            //$res=$service->compare_face($photo,2);
                            /*if($res['code']===0) {
                                $datas = $res['data']['results'];
                                if (count($datas) > 0) {
                                    return $datas[0];
                                } else {
                                    $post_ai_return_array = json_decode($post_ai_return, true);
                                    if ($post_ai_return_array['code'] === 0) {
                                        $res = $post_ai_return_array['data'];
                                        $data['photo_id'] = $res['photo_id'];
                                        $data['album_id'] = $res['album_id'];
                                        return $data;
                                    }
                                }
                            }//
                            Log::info("洞签新增人物：".$post_ai_return);
                            $post_ai_return_array = json_decode($post_ai_return, true);

                            if ($post_ai_return_array['code'] === 0) {
                                $res = $post_ai_return_array['data'];
                                return $res;
                            }
                        }

                    }
                }*/
            }
        }
        return [];
    }

    public function compare_by_album_ids($photo, $album_ids) {
        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        //实名库比较
        $res=$service->compare_face($photo,$album_ids);
        $res=json_decode($res,true);
        if($res['code']===0) {
            $datas = $res['data']['results'];
            if (count($datas) > 0) {
                return $datas[0];
            }
        }
        return 0;
    }

    public function compare_photo($photo,$start_time,$end_time) {
        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        //实名库比较
        $albums=Albums::where(['is_neijiang'=>1])->column('album_id');
        if($albums){
            $res=$service->compare_face($photo,$albums,$start_time,$end_time);
            $res=json_decode($res,true);
            if($res['code']===0) {
                return $res['data']['results'];
            }
        }
        return [];
    }

    public function compare_photo_feature($photo,$start_time,$end_time,$page,$limit,$score=0) {
        $log_id=md5($start_time.$end_time.$score.$photo);
        //获取提交图片feature
        $path=config('capture.capture_path').'/temp/'.date('Ym').'/'.date('d').'/';
        $id=time().rand(1000,9999);
        save_base_img($id,$photo,$path);
        $_calFeature=new CalFeature();
        $feature=$_calFeature->get_feature($path.$id.'.jpg');
        $data=[];
        $res['count']=0;
        Log::info($log_id."以图搜图获取feature");
        Log::debug($log_id."以图搜图获取feature:".$feature);
        if($feature) {
            //$score=config('capture.Local.max_feture');
            //$condition = $this->where('create_time', '>', $start_time);
            /*$condition = $this->where('feature_status', 1);
            if ($start_time) {
                $condition->where('create_time', '>', $start_time);
            }
            if ($end_time) {
                $condition->where('create_time', '<', $end_time);
            }
            $tasks = $condition->field('id,feature,feature_status,create_time,device_id,device_name,file_path')->select()->toArray();
            Log::info($log_id.'以图搜图-获取待查图片：'.count($tasks));*/
            /*$filters=[];
            foreach ($tasks as $task){
                if($task['feature_status']==1){
                    $filters[]=$task;
                }
            }
            $data=$this->dealTask($filters,$feature,$score,$log_id);*/
            //$data=$this->dealTask($tasks,$feature,$score,$log_id);
            $logic=config('capture.logic');
            if($logic){
                $_feature=new Feature();
                $res=$_feature->compare_feature2($feature,'album',$score,$log_id);
                if($res){
                    foreach ($res as $re) {
                        $ids[]=$re['id'];
                        $scores[$re['id']]=$re['score'];
                    }
                    $_face=new Faces();
                    $data=$_face->whereIn('photo_id',$ids)->whereBetweenTime('create_time',$start_time,$end_time)->order('scores','desc')->select()->toArray();
                    foreach ($data as &$single_face){
                        $single_face['score']=$scores[$single_face['photo_id']];
                    }
                    Cache::set($log_id,$data,3600);
                }
            }else{
                $data=$this->dealTask($start_time,$end_time,$feature,$score,0,$log_id);
            }
        }
        $res['count']=count($data);
        $res['lists']=array_slice($data,($page-1)*$limit,$limit);
        return $res;
    }
    public function compare_photo_features($photo,$start_time,$end_time,$page,$limit,$score) {
        $key=md5($photo).$start_time.$end_time.$score;
        if(!Cache::get($key)){
            $path=config('capture.capture_path').'/temp/'.date('Ym').'/'.date('d').'/';
            $id=time().rand(1000,9999);
            save_base_img($id,$photo,$path);
            $_calFeature=new CalFeature();
            $feature=$_calFeature->get_feature($path.$id.'.jpg');
            $news=[];
            $res['count']=0;
            if($feature){
                //$score=config('capture.Local.max_feture');
                $condition=$this->where('feature_status',1);
                if($start_time){
                    $condition->where('create_time','>',$start_time);
                }
                if($end_time){
                    $condition->where('create_time','<',$end_time);
                }
                $faces=$condition->select();

                foreach ($faces as $face){
                    if(!$face['feature'])continue;
                    $cal_score=$this->compare_feature_str($feature,$face['feature']);
                    Log::info('>>>>>>>>>'.$face['id'].'结果：'.$cal_score);
                    if($cal_score>$score){
                        $face['score']=$cal_score;
                        $news[]=$face;
                    }
                }
                uksort($news,function ($a,$b){
                    try {
                        return $a['score']>$b['score'];
                    }catch (\Exception $e){
                        Log::info("错误：".json_encode($a).json_encode($b));
                    }
                });
                Cache::set($key,$news,3600);

            }
        }else{
            $news=Cache::get($key);
        }
        $res['count']=count($news);
        $res['lists']=array_slice($news,($page-1)*$limit,$limit);
        return $res;
    }

    public function user_lost($day,$page,$limit){
        /*$sql="select * from  tp_mqtt_user_manage u
            left join (select * from tp_faces where photo_id !='' and photo_id !='0' create_time>'".date('Y-m-d H:i:s',strtotime('- 30 days'))."') f on u.photo_id=f.photo_id
            where u.photo_id !='' and u.photo_id !='0' and f.photo_id is null";*/
        $count_sql="select count(*) ";
        $select_sql="SELECT u.*";
        $sql=" FROM  tp_mqtt_user_manage u 
            LEFT JOIN tp_faces f ON u.photo_id=f.photo_id and f.photo_id !='' AND f.photo_id !='0' AND f.create_time>'".date('Y-m-d H:i:s',strtotime('- '.$day.' days'))."'  
            WHERE u.photo_id !='' AND u.photo_id !='0' AND f.photo_id IS NULL ";
        $count=Db::query($count_sql.$sql);
        $lists=Db::query($select_sql.$sql."limit ".($page-1)*$limit.','.$limit);
        return ['count'=>$count[0]['count(*)'],'lists'=>$lists];
    }

    public function stranger($all_day=30,$absent_day=20,$page=1,$limit=10){
        $count_sql="select count(*) ";
        $select_sql=" SELECT f.*";
        $sql=" FROM (
            SELECT * FROM (
                SELECT * FROM tp_faces 
                WHERE photo_id !='' AND photo_id !='0' AND create_time > '".date('Y-m-d H:i:s',strtotime('- '.$all_day.' days'))."' 
                GROUP BY photo_id,YEAR(create_time),MONTH(create_time),DAY(create_time)
            ) f 
            GROUP BY f.photo_id HAVING COUNT(*)>".$absent_day.") f 
            LEFT JOIN tp_mqtt_user_manage u ON u.photo_id=f.photo_id   
            WHERE  u.photo_id IS NULL ";
        $count=Db::query($count_sql.$sql);
        $lists=Db::query($select_sql.$sql." limit ".($page-1)*$limit.','.$limit);
        return ['count'=>$count[0]['count(*)'],'lists'=>$lists];
    }

    public function compare_feature($id) {
        /*\Swoole\Runtime::enableCoroutine(); // 启用协程
        Log::info("异步调用：".$id);
        go(function () use($id){
            $client = new \Swoole\Coroutine\Http\Client('127.0.0.1', 8081);
            $client->get('/job/compare_feature?id='.$id);
            Log::info("异步调用：".json_encode($client));
            $client->close();
        });*/
    }

    public function compare_feature_str($feature_src, $feature_dst) {
        // Base64解码
        $feature_src_dec = base64_decode($feature_src);
        $feature_dst_dec = base64_decode($feature_dst);

        // 计算二进制数据长度除以4（因为一个float占用4个字节）
        $feature_src_dec_size = intval(strlen($feature_src_dec) / 4);
        $feature_dst_dec_size = intval(strlen($feature_dst_dec) / 4);

        // 解包二进制数据为浮点数数组
        $src_feature_arr = unpack('f*', substr($feature_src_dec, 8));
        $dst_feature_arr = unpack('f*', substr($feature_dst_dec, 8));

        // 由于unpack返回的是关联数组，我们需要将其转换为数值数组
        $src_feature_arr = array_values($src_feature_arr);
        $dst_feature_arr = array_values($dst_feature_arr);

        // 计算点积
        $feature_dot_result = 0.0;
        for ($i = 0; $i < count($src_feature_arr); $i++) {
            $feature_dot_result += $src_feature_arr[$i] * $dst_feature_arr[$i];
        }

        // 计算模长
        $feature_x_result = 0.0;
        foreach ($src_feature_arr as $value) {
            $feature_x_result += $value * $value;
        }
        $feature_x_result = sqrt($feature_x_result);
        $feature_y_result = 0.0;
        foreach ($dst_feature_arr as $value) {
            $feature_y_result += $value * $value;
        }
        $feature_y_result = sqrt($feature_y_result);

        // 计算余弦相似度
        if(!($feature_x_result * $feature_y_result)){
            Log::info("计算错误：".$feature_dst);
            return 0;
        }
        $feature_cosine = $feature_dot_result / ($feature_x_result * $feature_y_result);

        // 输出结果
        //echo "cosine: " . $feature_cosine . ", score: " . $feature_cosine . "\n";
        Log::debug("对比结果：".$feature_cosine);
        return intval($feature_cosine*100);
    }

    /**
     * 获取底库比较最大值
     * @param array $all_people
     * @param $feature
     * @param $log_id
     * @return mixed 返回单条all_people的值，增加score字段
     */
    public function cal_max_feature(array $all_people,$feature,$log_id) {
        Log::info($log_id."获取底库比较最大值>>开始");
        $time=microtime(true);
        $configs=config('capture.Local');
        $score=$configs['max_feture'];
        $core=config('capture.sub_process');
        $size=count($all_people)/10;
        //Log::info($log_id."::size:".$size);
        if($size<1)$size=1;
        $tasks=array_chunk($all_people,$size);
        //Log::info($log_id."4");
        $taskProcess=new CalFeature();
        Log::info($log_id."获取底库比较最大值>>协程执行任务");
        foreach ($tasks as $task){
            $taskProcess->cal_max_feature($task,$feature,$score,$log_id);
        }
        $key="feature_".$feature;
        $num=Cache::get($key);
        Cache::delete($key);
        Log::info($log_id."获取底库比较最大值>>获取结果:".json_encode($num).',耗时'.(microtime(true)-$time));
        return $num;
    }

    /**
     * 对比face表中和智慧小区底库表中对比，并记录mqtt_user_manage底库的id
     * @param $id
     * @param $log_id
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function compare_feature_real($id,$log_id=0) {
        //Log::info("face处理》》》555:".$id);
        Log::info($log_id."保存face表>>和智慧小区底库比较feature>>");
        $feature=FacesFeature::find($id);
        $info=$this->find($id);
        if($info&&$feature){
            $feature=$feature['feature'];
            Log::debug($log_id."保存face表>>和智慧小区底库比较feature>>开始");
            $all_people=MqttUserManage::where('feature_status',1)->field('id,feature')->select()->toArray();
            if(count($all_people)>0){
                Log::debug($log_id."保存face表>>和智慧小区底库比较feature>>获取底库比较最大值>>开始");
                $single_data=$this->cal_max_feature($all_people,$feature,$log_id);
            }
            if(isset($single_data['id'])){
                Log::debug($log_id."保存face表>>获取最大值，保存face表，新增mqtt_face_push表数据,请求结束");
                //Log::info("face更新：");
                $info->mqtt_user_id = $single_data['id'];
                //$data['album_id'] = $single_data['album_id'];
                $info->mqtt_user_scores= $single_data['score'];
                $info->save();
                $info->score=$info->mqtt_user_scores;
                $user=MqttUserManage::find($single_data['id']);
                MqttFacePushInfo::insert_compare_result((array_merge($user->toArray(),$info->toArray())));
                return $info;
            }else{
                Log::debug($log_id."保存face表>>未获取最大值,请求结束");
            }
        }
        return null;

    }

    /**
     * 获取历史feature
     * @return void
     */
    public function get_face_feature() {
        $lists=$this->where('feature_status',0)->order("id desc")->limit(20000)->field('id,file_path,feature_status,create_time')->select();
        $_calFeature=new CalFeature();

        foreach ($lists as $list) {
            $data=[];
            $_feature=new FacesFeature();
            $file=$list['file_path'].$list['id'].'_face.jpg';
            if(file_exists($file)){
                $feature=$_calFeature->get_feature($file);
                //Log::info("获取feature:".json_encode($feature));
                if($feature){
                    //$list->feature=$feature;
                    $list->feature_status=1;
                    $data['feature']=$feature;
                    $data['create_time']=$list->create_time;
                    $data['id']=$list->id;
                    $_feature->save($data);
                }else{
                    $list->feature_status=2;
                }
            }else{
                $list->feature_status=3;
            }
            $list->save();
        }
    }

    //private function dealTask(array $tasks, $feature, $score, string $log_id) {
    private function dealTask($start_time,$end_time, $feature, $score, $photo_id,string $log_id) {
        $configs=config('capture.Local');
        if(!$score){
            $score=$configs['max_feture'];
        }
        $start_time=strtotime($start_time);
        $end_time=strtotime($end_time);
        $core=config('capture.sub_process');
        //所有天数
        $all_day=ceil(($end_time-$start_time)/(3600*24));
        $count=ceil($all_day/$core);
        if($count<2){
            $core=ceil($all_day/2);
            $size=2;
        }else{
            $size=ceil($all_day/$core);
        }
        //$core=80;
        //$size=count($tasks)/$core;
        //$tasks=array_chunk($tasks,$size);
        Log::info($log_id."进程处理总数：".$core.',每个处理任务天数：'.$size);
        $end_time=$start_time;
        $start_time-=$size*3600*24;
        for ($i=0;$i<$core;$i++){
            $start_time+=$size*3600*24;
            $end_time+=$size*3600*24;
            $content=json_encode([
                'start_time'=>$start_time,
                'end_time'=>$end_time,
                //'task' => $task,
                'score' => $score,
                'feature' => $feature,
                'log_id'=>$log_id,
                'photo_id'=>$photo_id,
                'main_id'=>$i
            ]);
            $job_data = [];
            $job_data["ts"] = time();
            $job_data["bizid"] = uniqid();
            $job_data["params"] =$content;
            $is_pushed=Queue::push(CompareFeature::class,$job_data,'compare_feature',false);
            //Log::info($log_id.":第".$i."次投递任务：".$is_pushed);
        }
        /*foreach ($tasks as $key=>$task) {
            $content=json_encode([
                'task' => $task,
                'score' => $score,
                'feature' => $feature,
                'log_id'=>$log_id
            ]);
            $job_data = [];
            $job_data["ts"] = time();
            $job_data["bizid"] = uniqid();
            $job_data["params"] =$content;
            $is_pushed=Queue::push(CompareFeature::class,$job_data,'compare_feature',false);
            Log::info($log_id.":第".$key."次投递任务：".$is_pushed);
        }*/
        $results=[];
        for($i=0;$i<60;$i++){
            /*if(Cache::has($log_id)){
                $temps=Cache::get($log_id);
                Log::info($log_id."，第".$i."次获取结果：".count($temps));
                if(count($temps)>=$core){
                    foreach ($temps as $temp){
                        if(!empty($temp)){
                            $results=array_merge($results,$temp);
                        }
                    }
                    uksort($results,function ($a,$b){
                        try {
                            return $a['score']>$b['score'];
                        }catch (\Exception $e){
                            Log::info("错误：".json_encode($a).json_encode($b));
                        }
                    });
                    Cache::set($log_id,$results,3600);
                    break;
                }
            }*/
            $full=true;
            $temps=[];
            for ($j=0;$j<$core;$j++){
                if(!Cache::has($log_id.'_'.$j)){
                    //Log::info($log_id."，第".$i."次获取结果不存在主线程：".$j);
                    $full=false;
                    break;
                }else{
                    $temps=array_merge($temps,Cache::get($log_id.'_'.$j));
                }
            }
            if($full){
                //Log::info("所有结果：".json_encode($temps));
                uksort($temps,function ($a,$b) use ($temps) {
                    try {
                        //Log::info("比较大小:".json_encode($a));
                        return $temps[$a]['score']<$temps[$b]['score'];
                    }catch (\Exception $e){
                        Log::info("错误：".json_encode($a).'__'.json_encode($b));
                    }
                });
                Cache::set($log_id,$temps,3600);
                $results=$temps;
                break;
            }
            sleep(1);
        }
        return $results;
    }

    public function compare_all_by_ablum_photo($feature,$photo_id,$log_id){
        $config=config('capture.Local');
        $score=$config['max_feture'];
        $start_time='1900-01-01 00:00:00';
        $end_time='2100-01-01 00:00:00';
        $this->dealTask($start_time,$end_time, $feature, $score, $photo_id,$log_id);
    }

    /**
     * 接收摄像头摄像头图片后，
     * 1、计算特征值
     * 2、和战法底库进行比较
     * 3、推送洞鉴
     * 4、更新face表，新增FacesFeature数据
     * //5、和智慧小区底库表中对比(注销)
     * 6、使用战法底库布控
     * @param $face_id
     * @param $log_id
     * @param $ts
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     */
    public function cal_face($face_id, $log_id, $ts) {
        $_calFeature=new CalFeature();
        $_album_photo=new AlbumPhoto();
        $_album_people=new AlbumPeople();
        $data=$this->find($face_id);
        //$path=config('capture.capture_path').'/'.$face['DeviceID'].'/'.date('Ym').'/'.date('d').'/';
        //计算特征值
        $feature=$_calFeature->get_feature($data['file_path'].$data['id'].'_face'.'.jpg',$log_id);
        if($feature){
            Log::info($log_id."保存face表>>获取feature值并保存");
            $data['feature_status']=1;
            //和战法底库进行比较
            $photo_res=$_album_photo->compare_face_feature($feature,$log_id,false);
            if($photo_res){
                Log::info($log_id."保存face表>>布控计算");
                $device=ViidDevice::where('device_id','=',$data['device_id'])->find();
                Log::info($log_id."保存face表>>布控计算:".json_encode($photo_res));
                $data['photo_id']=$photo_res['id'];
                $data['scores']=round($photo_res['score']*100,2);
                //$photo=$_album_photo->find($photo_re['id'])->toArray();
                //$photos=$_album_people->where('photo_id',$photo_res['id'])->select();
                $people=$_album_people->find($photo_res['id']);
                $photos=$_album_photo->where('people_id','=',$photo_res['id'])->select();
                $album_names=[];
                foreach ($photos as $photo) {
                    if ($photo['album_id'] > 0) {
                        $album = Albums::find($photo['album_id'])->toArray();
                        $album_names[] = $album['name'];
                        //布控
                        $tasks = Task::getAvaTask($device['id'], $photo['album_id']);
                        if ($tasks) {
                            foreach ($tasks as $task) {
                                //洞签接口
                                //$res = $this->compare_by_album_ids('image/jpeg;base64,'.$images[1]['Data'], [$task['album_id']]);
                                //本地底库
                                //$res=AlbumPhoto::comparePhoto($single_data['feature'],$log_id);
                                $task['push_id'] = $photo_res['id'];
                                $task['photo_id'] = $photo_res['id'];
                                $task['queue'] = 1;
                                $task['face_id'] = $face_id;
                                $task['find_device_id'] = $data['device_id'];
                                //$task['dongjian_result']=json_encode($res);
                                Task::finishTask($task, 1);
                            }

                        }
                    } elseif ($photo['album_id'] == -2) {
                        $this->delete();
                        Log::debug($log_id . "保存face表>>黑名单用户，删除。" . $photo['id']);
                        return;
                    }
                }

                //发送websocket
                $push_data['msg_type'] = 'albumalert';
                $push_data['data']['face'] = $data;
                $photo['album_name'] = implode(',', $album_names);
                $push_data['data']['photo'] = $people;
                Http::post('http://127.0.0.1:9503', ['content' => json_encode($push_data)]);
                $_album_people->where('id',$photo_res['id'])->save(['last_time'=>date('Y-m-d H:i:s'),'show_num'=>Db::raw('show_num+1')]);
            }else{
                $data['photo_id']=$_album_people->create_data($feature,$data['file_path'].$data['id'].'_face'.'.jpg');
                $_album_photo->create_data($data['photo_id'],$data['file_path'].$data['id'].'_face'.'.jpg');
                $data['scores']=100;
            }
            Log::debug("保存face表>>更新photo_id".$log_id.json_encode($data));
            $data->save();
            $feature_data['feature']=$feature;
            $feature_data['id']=$data['id'];
            $feature_data['create_time']=date('Y-m-d H:i:s');

            FacesFeature::create($feature_data);
            //$data['feature']=$feature;
            //$single_data=$this->compare('data: image/png;base64,'.$images[1]['Data'],$data);
            //$this->compare_feature($this->id);
            //和智慧小区底库表中对比
            //$single_data=$this->compare_feature_real($face_id,$log_id);

            Log::info($log_id."———保存face表>>任务全部结束");
        }else{
            $data['feature_status']=2;
            $data->save();
            Log::info($log_id."———保存face表>>未算出feature值");
        }

    }

    public function save_face_photo_id($id=0) {
        if($id){
            $lists=$this->where('id',$id)->select();
        }else{
            $lists=$this->where('feature_status',1)->where('photo_id','')->limit(1)->select();
        }
        $_face_feature=new FacesFeature();
        $_feature=new Feature();
        $_album_photo=new AlbumPhoto();
        foreach ($lists as $list){
            Log::info("save_:::".json_encode($list));
            $info=$_face_feature->find($list['id']);
            $photo_id=0;
            if($info['feature']){
                $results=$_feature->compare_feature($info['feature'],'album',config('capture.Local.max_feture'),time());
                if($results){
                    $result=$results[0];
                    $photo=$_album_photo->find($result['id']);
                    if($photo->album_id=-2){
                        $photo->delete();
                    }
                    //$_album_photo->where('id',$result['id'])->inc('show_num')->save();
                    $photo_id=$result['id'];
                }else{
                    $photo_id=$_album_photo->create_data($info['feature'],$info['file_path'].$info['id'].'_face'.'.jpg');
                }
            }
            $this->where('id',$list['id'])->save(['photo_id'=>$photo_id]);
        }
    }

    public function delete_not_record() {
        Db::startTrans();
        try{
            $_photo=new AlbumPhoto();
            $ids=$_photo->where('album_id',-2)->column('id');
            Log::info("要删除的photo_id:".json_encode($ids));
            $del_ids=$this->whereIn('photo_id',$ids)->column('id');
            if($del_ids){
                Log::info("要删除的id:".json_encode($del_ids));
                $this->whereIn('id',$del_ids)->delete();
                $_face_feature=new FacesFeature();
                $_face_feature->whereIn('id',$del_ids)->delete();
            }
            Db::commit();
        }catch (\Exception $e){
            Log::error($e->getTraceAsString());
            Db::rollback();
        }

    }
}